package com.zjxf.redis.impl;

import com.alibaba.fastjson.JSONObject;
import com.zjxf.redis.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * author: create by ZhangHao
 * Date: 2019/7/24
 * Time: 18:32
 */
@Service
public class RedisServiceImpl implements RedisService {

    @Autowired
    private RedisTemplate redisTemplate;
    private static boolean newValue1;

    @Override
    public Optional<JSONObject> get(String key) {
        ValueOperations<String, JSONObject> valueOperations = redisTemplate.opsForValue();
        return Optional.ofNullable(valueOperations.get(key));
    }

    @Override
    public void setContainExpire(String key, JSONObject value) {
        ValueOperations<String, JSONObject> valueOperations = redisTemplate.opsForValue();
        valueOperations.set(key, value, 30, TimeUnit.MINUTES);
    }

    @Override
    public void setContainExpire(String key, JSONObject value, long timeout, TimeUnit unit) {
        ValueOperations<String, JSONObject> valueOperations = redisTemplate.opsForValue();
        valueOperations.set(key, value, timeout, unit);
    }

    @Override
    public void setNotContainExpire(String key, JSONObject value) {
        ValueOperations<String, JSONObject> valueOperations = redisTemplate.opsForValue();
        valueOperations.set(key, value);
    }

    @Override
    public Set<String> keys(String key) {
        return redisTemplate.keys(key);
    }

    @Override
    public void flushDB() {
        redisTemplate.execute((RedisCallback<String>) connection -> {
            connection.flushDb();
            return "ok";
        });
    }

    @Override
    public Collection<JSONObject> keysValue(String key) {
        return redisTemplate.keys("*");
    }

    @Override
    public Long dbSize() {
        return null;
    }

    @Override
    public Boolean delete(String key) {
        return redisTemplate.delete(key);
    }

    @Override
    public void receiveMessage(String message) {
        System.out.println("message = " + message);
    }

}
